package com.ywd.platform.netty.jt080.service;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Component
public class TerminalConnectionManager {

    private final ConcurrentMap<String, Channel> terminalChannels = new ConcurrentHashMap<>();
    private final ConcurrentMap<Channel, String> channelTerminals = new ConcurrentHashMap<>();

    /**
     * 绑定终端到通道
     */
    public void bindTerminal(String terminalPhone, Channel channel) {
        terminalChannels.put(terminalPhone, channel);
        channelTerminals.put(channel, terminalPhone);
        log.info("终端绑定成功: {} -> {}", terminalPhone, channel.remoteAddress());
    }

    /**
     * 解绑终端
     */
    public void unbindTerminal(String terminalPhone) {
        Channel channel = terminalChannels.remove(terminalPhone);
        if (channel != null) {
            channelTerminals.remove(channel);
            log.info("终端解绑成功: {}", terminalPhone);
        }
    }

    /**
     * 解绑通道
     */
    public void unbindChannel(Channel channel) {
        String terminalPhone = channelTerminals.remove(channel);
        if (terminalPhone != null) {
            terminalChannels.remove(terminalPhone);
            log.info("通道解绑成功: {} -> {}", terminalPhone, channel.remoteAddress());
        }
    }

    /**
     * 获取终端通道
     */
    public Channel getChannel(String terminalPhone) {
        return terminalChannels.get(terminalPhone);
    }

    /**
     * 获取通道终端
     */
    public String getTerminal(Channel channel) {
        return channelTerminals.get(channel);
    }

    /**
     * 检查终端是否在线
     */
    public boolean isOnline(String terminalPhone) {
        Channel channel = terminalChannels.get(terminalPhone);
        return channel != null && channel.isActive();
    }

    /**
     * 获取所有在线终端
     */
    public Set<String> getOnlineTerminals() {
        return terminalChannels.keySet();
    }

}
